// API服务，与json-server交互
const API_BASE_URL = 'http://localhost:3000'

class ApiService {
  // 通用请求方法
  async request(url, options = {}) {
    const response = await fetch(`${API_BASE_URL}${url}`, {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      ...options
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return response.json()
  }

  // 用户相关API
  async getUsers() {
    return this.request('/users')
  }

  async getUser(id) {
    return this.request(`/users/${id}`)
  }

  async createUser(userData) {
    return this.request('/users', {
      method: 'POST',
      body: JSON.stringify(userData)
    })
  }

  async updateUser(id, userData) {
    return this.request(`/users/${id}`, {
      method: 'PATCH',
      body: JSON.stringify(userData)
    })
  }

  async deleteUser(id) {
    return this.request(`/users/${id}`, {
      method: 'DELETE'
    })
  }

  // 根据用户名获取用户
  async getUserByUsername(username) {
    const users = await this.request(`/users?username=${username}`)
    return users[0] || null
  }

  // 课程相关API
  async getCourses() {
    return this.request('/courses')
  }

  async getCourse(id) {
    return this.request(`/courses/${id}`)
  }

  async createCourse(courseData) {
    return this.request('/courses', {
      method: 'POST',
      body: JSON.stringify(courseData)
    })
  }

  async updateCourse(id, courseData) {
    return this.request(`/courses/${id}`, {
      method: 'PATCH',
      body: JSON.stringify(courseData)
    })
  }

  async deleteCourse(id) {
    return this.request(`/courses/${id}`, {
      method: 'DELETE'
    })
  }

  // 根据教师名称获取课程
  async getCoursesByTeacher(teacherName) {
    return this.request(`/courses?teacher=${teacherName}`)
  }

  // 获取可选课程
  async getAvailableCourses() {
    return this.request('/courses?status=open')
  }
}

export const apiService = new ApiService()
export default apiService